import React, {useEffect, useState} from "react";
import {
    Button,
    Col,
    Form,
    Input,
    message,
    Modal,
    Row,
    Select,
    Space,
    Switch,
    Table,
    TableProps,
    Tooltip,
} from 'antd';
import renderIcons from "@/components/CustomIconSelector/conponents";
import {DeleteOutlined} from "@ant-design/icons";
import {useNavigate} from "react-router-dom";
import {
    definitionDelete,
    definitionStatus, getProcessDefinition,
    getProcessDefinitionXml,
    processDefinitionList
} from "@/api/flowable/definition";
import AddMyTaskView from "@/views/flowable/task/myProcess/component/addMyTaskView";
import PrcessView from "@/components/prcessView";
import useResponsiveLayout from "@/utils/useResponsiveLayout";
import { globalMessage } from "@/utils/message";

const DefinitionView: React.FC = () => {
    const initialQueryParams = {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        category: undefined,

    };

    interface DataType {
    }

    const navigateTo = useNavigate();
    const [form] = Form.useForm();
    const [record, setRecord] = useState<Record<string, any>>({});
    const [forceUpdateKey, setForceUpdateKey] = useState(0); // 用于强制更新组件的 key
    const [dataList, setDataList] = useState<DataType[]>([]);
    const [processViewOpen, setProcessViewOpen] = useState(false);//点击查看流程图
    const [processKeys, setProcessKeys] = useState<string|null>(null);
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '流程名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center'
        },
        {
            title: '流程分类',
            dataIndex: 'category',
            key: 'category',
            align: 'center'
        },
        {
            title: '流程标识',
            dataIndex: 'key',
            key: 'key',
            align: 'center'
        }, {
            title: '版本',
            dataIndex: 'version',
            key: 'version',
            align: 'center'
        }, {
            title: '状态',
            dataIndex: 'suspensionState',
            key: 'suspensionState',
            align: 'center',
            render: (_, record:any) => (
                <Switch key={forceUpdateKey + record.id} defaultValue={record.suspensionState === 1}
                        onChange={(checked, event) => onChangeStatus(checked, event, record)} checkedChildren="激活"
                        unCheckedChildren="挂起"/>
            )
        }, {
            title: '创建时间',
            dataIndex: 'deploymentTime',
            key: 'deploymentTime',
        }, {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            fixed: 'right',
            render: (_, record:any) => (
                <Space size="middle">
                    {record?.roleId !== 1 && (
                        <Tooltip title="设计">
                            <Button
                                type="link"
                                size="small"
                                icon={renderIcons("edit")}
                                onClick={() => EditClick(record)}/>
                        </Tooltip>

                    )}
                    {record?.roleId !== 1 && (
                        <Tooltip title="流程图">
                            <Button
                                type="link"
                                size="small"
                                icon={renderIcons("edit")}
                                onClick={() => handleProcessView(record)}/>
                        </Tooltip>

                    )}
                    {record?.roleId !== 1 && (
                        <Tooltip title="删除">
                            <Button
                                type="link"
                                size="small"
                                icon={<DeleteOutlined/>}
                                onClick={() => handleDelete(record)}/>
                        </Tooltip>
                    )}

                </Space>
            ),
        },
    ];
    const [queryParams, setQueryParams] = useState(initialQueryParams);
    const [total, setTotal] = useState(0);
    const [openDataPermissions, setOpenDataPermissions] = useState<boolean>(false);
    useEffect(() => {
        getList();
    }, [queryParams]);  // 监听 queryParams 变化，调用 getList

    /** 查询用户列表 */
    function getList() {
        processDefinitionList(queryParams).then((res:any) => {
            setDataList(res.rows.map((item: any) => ({
                ...item,
                // key: item.id // 使用 userId 作为唯一的 key
            })))
            setTotal(res.total); // 更新 total，用于分页
        });
    }

    // 查询列表
    function handleSearch() {
        form.validateFields().then(values => {
            console.log(values, 'values')
            setQueryParams(prevQueryParams => ({
                ...queryParams,
                name: values.name,
                category: values.category,
            }));
        });
    }

    // 重置查询
    const resetSearch = () => {
        form.resetFields();
        setQueryParams(initialQueryParams); // 重置为初始状态
    }

    // 分页变化
    const handleTableChange = (page: number, pageSize: number) => {
        setQueryParams({
            ...queryParams,
            pageNum: page,
            pageSize: pageSize,
        });
    };
    // 修改按钮
    const EditClick = (e: any) => {
        console.log("e", e)
        navigateTo('/system/flowable/editdefinition', {
            state: {
                key: e.key,
            },
        })

    }
    // 删除按钮
    const handleDelete = (e: any) => {
        const roleIds = e.deploymentId;
        Modal.confirm({
            title: '系统提示',
            content: (`是否确认删除用户编号为"${roleIds}"的数据项？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                definitionDelete(roleIds).then((res: any) => {
                    if (res?.code === 200) {
                         globalMessage().info("删除成功")
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作

            },
        });

    }
    const onChangeStatus = (checked: boolean, event: any, value: any) => {
        console.log(checked, event, value);
        const text = value.suspensionState === "1" ? "启用" : "停用";
        Modal.confirm({
            title: '系统提示',
            content: (`确认要"${text}"+"${value.name}"流程吗？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                definitionStatus(value.id, checked === false ? "2" : "1").then((res:any) => {
                    if (res?.code === 200) {
                         globalMessage().info("修改成功").then(r => {
                        })
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作
                setForceUpdateKey(prevKey => prevKey + 1); // 更新 key 以强制重新渲染组件
            },
        });
        // console.log(checked,event,value,value.status == "0")
    }
    // 查看流程图
    const handleProcessView = (e) => {

        getProcessDefinition(e.key).then((res:any) => {
            if (res.code == 200) {
                setProcessKeys(e.key);
                setProcessViewOpen(true);
            }

        })


    }
    return (
        <div className='home'>
            <Row gutter={20} style={{paddingTop: "20px"}}>
                <Col span={24}>
                    <div><Form
                        form={form}
                        name="definition_form_controls"
                        style={{marginTop: 10, marginLeft: 10, marginBottom: 10}}
                       layout={useResponsiveLayout("inline")}>
                        <Form.Item
                            name="name"
                            label="流程名称">
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            name="category"
                            label="流程分类">
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            name="status"
                            label="状态">
                            <Select
                                style={{
                                    width: 120,
                                }}

                                allowClear
                                options={[
                                    {
                                        value: 0,
                                        label: '正常',
                                    }, {
                                        value: 1,
                                        label: '停用',
                                    },
                                ]}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" onClick={handleSearch} style={{
                                marginRight: 20,
                            }}>
                                查询
                            </Button>
                            <Button type="primary" htmlType="reset" onClick={resetSearch}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form></div>
                    <div><Button type="primary" ghost onClick={() => {
                        navigateTo('/system/flowable/editdefinition')
                    }} style={{margin: 10}}>
                        新增
                    </Button></div>
                    <Table<DataType>
                        rowKey="id"
                        columns={columns}
                        dataSource={dataList}
                        scroll={{ x: true }}
                        pagination={{
                            current: queryParams.pageNum,
                            pageSize: queryParams.pageSize,
                            total: total,
                            showSizeChanger: true, // 显示分页尺寸切换器
                            pageSizeOptions: ['10', '20', '50'], // 分页尺寸选项
                            onShowSizeChange: handleTableChange, // 分页尺寸变化时的回调
                            onChange: handleTableChange
                        }}/>
                </Col>
            </Row>
           {processViewOpen&& <Modal width="70%"
                  title="新增流程"
                   open={processViewOpen}
                   footer={null}
                   onCancel={() => setProcessViewOpen(false)}>
                <PrcessView processKeys={processKeys}></PrcessView>
            </Modal>}
        </div>
    )
};
export default DefinitionView;
